﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace MyCourseManager.Common
{
    public class PasswordHelper
    {
        /// <summary>
        /// 定义依赖属性及其回调
        /// </summary>
        public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordHelper), new PropertyMetadata("", new PropertyChangedCallback(OnPropertyChanged)));

        public static void SetPassword(DependencyObject d,string value)
        { 
            d.SetValue(PasswordProperty, value);
        }

        public static string GetPassword(DependencyObject d)
        { 
           return d.GetValue(PasswordProperty)?.ToString();
        }

        public static bool isUpdating = false;

        /// <summary>
        /// 前端修改后触发依赖属性change事件,1.修改控件值 2.修改依赖值
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordbox = d as PasswordBox;
            passwordbox.PasswordChanged -= passwordchanged;
            if (!isUpdating)
            {
                passwordbox.Password = e.NewValue?.ToString();//更新passwordbox的值
            }
            passwordbox.PasswordChanged += passwordchanged;//重新挂载自定义的password修改事件修改依赖
        }



        public static readonly DependencyProperty AttachProperty =
        DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(default(bool), new PropertyChangedCallback(AttachChanged)));
        public static bool GetAttach(DependencyObject d)
        {
            return (bool)d.GetValue(AttachProperty);
        }
        public static void SetAttach(DependencyObject d, bool value)
        {
            d.SetValue(AttachProperty, value);
        }

        private static void AttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox password = d as PasswordBox;
            password.PasswordChanged += passwordchanged;
        }


        private static void passwordchanged(object sender, RoutedEventArgs e)
        {
            PasswordBox passwordbox = sender as PasswordBox;
            isUpdating = true;
            SetPassword(passwordbox, passwordbox.Password);
            isUpdating = false;
        }
    }
}
